#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    init();
    db_init();
    db_select();
    this->setFixedSize(1050,650);
    this->setWindowTitle("绿洲智联");

    connect(m_MonitorWidget,&MonitorWidget::ErrorResetBtn_push,this,&MainWindow::ser_init);//连接
    connect(m_MonitorWidget,&MonitorWidget::ProductEndBtn_push,this,[=](){
        this->close();
    });//结束

}

void MainWindow::ser_init(int b)
{
    //串口
    seriaport=new QSerialPort();
    seriaport->setPortName("COM3");//待打开的串口号
    seriaport->setBaudRate(b,QSerialPort::AllDirections);
    seriaport->setDataBits(QSerialPort::Data8);
    seriaport->setParity(QSerialPort::NoParity);//校验位
    seriaport->setStopBits(QSerialPort::OneStop);//停止位
    seriaport->setFlowControl(QSerialPort::NoFlowControl);//流控制

    connect(seriaport,&QSerialPort::readyRead,this,&MainWindow::readbuffer);
}

void MainWindow::readbuffer()
{
    QByteArray dataArray;
    QMessageBox message(QMessageBox::NoIcon, "警告", "温湿度超限！！",QMessageBox::Ok);
     struct da1{
         short a;
         short b;
         char c;
       }__attribute__((packed));

    dataArray = seriaport->readAll();
    if (!dataArray.isEmpty()) {
       const da1 *da=(const da1 *)(dataArray.data());
         qDebug()<<da->a;
         qDebug()<<da->b;
         qDebug()<<da->c;

         if(da->a>((float)dd.setTemp/10)||da->b>((float)dd.setHum/10))
         {

            if(messageBox==false)
              {
                messageBox=true;
                //
                //降温程序
                //
                message.exec();
              }
            qDebug()<<"  "<<message.isActiveWindow();
         }
    }
}

void MainWindow::db_init()
{
    //添加驱动
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //打开数据库（不存在则创建）
    db.setDatabaseName("object.db");
    qDebug()<<"open object.db";

    if(!db.open()){
        qDebug()<<"open object.db failed";
    }

    //创建表

    QSqlQuery query;

    QString sql = "CREATE TABLE IF NOT EXISTS oasis ("
                  "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                  "temperature REAL, "
                  "humidity REAL, "
                  "illumination INTEGER);";

    if (! query.exec(sql)){
        qDebug()<<"create table failed";
    }
}

bool MainWindow::db_update()
{
    if(!QSqlDatabase::database().isOpen()){ // 检查连接状态
        qDebug()<<"Database not open!";
        return false;
    }

    QSqlQuery query;
    QString sql = "UPDATE oasis SET temperature=:temp, humidity=:hum, illumination=:illum WHERE id=:id";

    if(!query.prepare(sql)){
        qDebug()<<"Prepare failed: ";
        return false;
    }

    query.bindValue(":temp", QString::number(dd.setTemp)); // 显式类型转换
    query.bindValue(":hum", QString::number(dd.setHum));
    query.bindValue(":illum", QString::number(dd.setillum));
    query.bindValue(":id", 1); // 建议使用动态ID

    if(!query.exec()){
        qDebug()<<"Execute failed: ";
        return false;
    }

    return true;
}
bool MainWindow::db_select()
{
    QString sql = QString("select * from oasis where id = '%1';").arg(1);
    qDebug()<<sql;

    QSqlQuery query;

   if(! query.exec(sql)){
       qDebug()<<"select failed";
       return false;
   }

   if(query.next())
   {
       dd.setTemp = query.value("temperature").toInt();
       dd.setHum = query.value("humidity").toInt();
       dd.setillum = query.value("illumination").toInt();
   }
   return true;
}

MainWindow::~MainWindow()
{
    if (seriaport) {
        seriaport->close();
        delete seriaport;  // 原代码缺少 delete
    }
    QSqlDatabase::database().close();
    m_timer.stop();
    delete ui;
}

void MainWindow::init()
{

    // 初始化导航栏按钮
    for(int i = 0 ; i<6;i++)
    {
        NavBtn* btn = new NavBtn(ui->widgetNav);
        btn->setMinimumWidth(110);
        btn->setIndex(i);
        switch (i) {
        case 0:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav2.png);",tr("监视画面"));
            btn->setClickedStyle();
            ui->stackedWidget->setCurrentIndex(0);
            break;
        case 1:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav3.png);",tr("手动操作"));
            break;
        case 2:
            btn->setPicName("border-image: url(:/new/prefix1/Resource/Nav4.png);",tr("AI预测"));
            break;
        case 3:
            btn->setPicName("border-image: url();",tr(""));
            break;
        case 4:
            btn->setPicName("border-image: url();",tr(""));
            break;
        case 5:
            btn->setPicName("border-image: url();",tr(""));
            break;
        default:
            break;
        }

        m_NavBtnMap.insert(btn->getName(),btn);
        ui->verticalLayoutNav->addWidget(btn);

        connect(btn,&NavBtn::sigClicked,[=](QString name)
        {
            QMap<QString,NavBtn*>::Iterator item = m_NavBtnMap.begin();
            while (item != m_NavBtnMap.end()) {
                if(item.key() != name)
                {
                    ((NavBtn*)(item.value()))->setNormalStyle();
                }
                item++;
            }
            ui->stackedWidget->setCurrentIndex(m_NavBtnMap.value(name)->getIndex());
        });
       }



    ui->labelTime->setText(QDateTime::currentDateTime().toString("yyyy:MM:dd hh:mm:ss").replace(" ","\n"));
    connect(&m_timer,&QTimer::timeout,[=]
    {
         ui->labelTime->setText(QDateTime::currentDateTime().toString("yyyy:MM:dd hh:mm:ss").replace(" ","\n"));
    });
    m_timer.start(1000);


   //初始化监控界面
    m_MonitorWidget = new MonitorWidget(ui->pageMonitor);
    ui->verticalLayoutMonitor->addWidget(m_MonitorWidget);
    //初始化手动界面
    m_HandWidget = new HandWidget(ui->pageHand);
    ui->verticalLayoutHandle->addWidget(m_HandWidget);

    //初始化参数界面
    m_ParamterWidget = new ParamterWidget(ui->pageParamter);
    ui->verticalLayoutParamter->addWidget(m_ParamterWidget);

}


